﻿using Microsoft.AspNetCore.Mvc;
using STF.Blog.IService;
using STF.Blog.WebApp.Areas.ForumManage.Models.FriendLink;
using X.PagedList;
using STF.Blog.Common;
using STF.Blog.WebApp.Areas.ForumManage.Filters;

namespace STF.Blog.WebApp.Areas.ForumManage.Controllers
{
    [Area("ForumManage")]
    [Login]
    public class FirendLinkController : Controller
    {

        private IFriendLinkService _ifs;
        public FirendLinkController(IFriendLinkService ifs)
        {
            _ifs = ifs;
        }

        public async Task<IActionResult> Index(string search,int page = 1)
        {
            search = string.IsNullOrEmpty(search) ? "" : search;
            var data = await _ifs.GetDateByName(search);

            var FriendList = data.Select(fl => new FriendLinkListViewModel 
            {
                Id = fl.Id,
                Title = fl.Title,
                Link = fl.Link,
                UpdateTime = fl.UpdateTime,
            }).ToList();
            
            ViewBag.Search = search;
            var pages = await FriendList.ToPagedListAsync(page, PageConfig.PageSize);
            return View(pages);
        }

        [HttpPost]
        public async Task<IActionResult> Delete(int id) 
        {
            await _ifs.PutTrashAsync(id);
            return Redirect("~/ForumManage/FirendLink/Index");
        }

        [HttpGet]
        public async Task<IActionResult> Add() 
        {
            return View(new FriendLinkAddViewModel());
        }

        [HttpPost]
        public async Task<IActionResult> Add(FriendLinkAddViewModel model) 
        {
            if (ModelState.IsValid) 
            {
                await _ifs.AddUsersAsync(model.Title,model.Link);
                return Redirect("~/ForumManage/FirendLink/Index");
            }
            return View(model);
        }

        [HttpGet]
        public async Task<IActionResult> Update(int id) 
        {
            var data = await _ifs.GetDateById(id);

            return View(new FriendLinkUpdateViewModel 
            {
                Id = data.Id,
                Title = data.Title,
                Link = data.Link
            });
        }

        [HttpPost]
        public async Task<IActionResult> Update(FriendLinkUpdateViewModel model) 
        {
            await _ifs.UpdateUsersAsync(model.Id,model.Title, model.Link);
            return Redirect("~/ForumManage/FirendLink/Index");
        }
    }
}
